<script setup>

import * as mqtt from "mqtt/dist/mqtt.min";
import {onMounted, ref, watch} from "vue";

// 连接选项
const options = {
      clean: true, // true: 清除会话, false: 保留会话
      connectTimeout: 4000, // 超时时间
      // 认证信息
      clientId: 'emqx_test',
      username: 'emqx_test',
      password: 'emqx_test',
}

// 连接字符串, 通过协议指定使用的连接方式
// ws 未加密 WebSocket 连接
// wss 加密 WebSocket 连接
// mqtt 未加密 TCP 连接
// mqtts 加密 TCP 连接
// wxs 微信小程序连接
// alis 支付宝小程序连接
const connectUrl = 'ws://122.51.127.33:8083/mqtt'
const client = mqtt.connect(connectUrl, options)

client.on('connect', function () {
    console.log('Connected to MQTT broker')
    client.subscribe('/topic1')
})



client.on('error', (error) => {
    console.log('连接失败:', error)
  client.on('reconnect', (error) => {
    console.log('正在重连:', error)
})
})
const sub = ref('')
client.on('message', (topic, message) => {
  sub.value = message.toString()
  console.log('收到消息：', topic, message.toString())
})
const mqtt_pub = ref('')
const time = ref('0')
watch(sub,()=>{
  time.value=new Date()
})
const pub =()=>{client.publish('/topic1', mqtt_pub.value, {
    qos: 1
})}

</script>

<template>

  <div>发布：<el-input v-model="mqtt_pub" class="w-50 m-2"
      size="large"/>
<el-button @click="pub">提交</el-button> <el-link type="success" href="http://wzmzero.top:18083/#/">跳转到mqtt后台服务器</el-link>
  {{ mqtt_pub }}</div>
  <br>{{time}}<br><br>
  <div>订阅：{{sub}}</div>
</template>

<style scoped>

</style>